package com.java2007.hotel.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author csl
 * @version V1.0
 * @date 2021/01/05
 **/
public class JdbcUtils {
    private static DataSource dataSource = null;
    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
    static {
        InputStream is = null;
        try {
            is = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static DataSource getDataSource (){
        return dataSource;
    }


    public static Connection getConnection(){
        Connection connection = tl.get();
        if (connection == null){
            Connection connection1 = null;
            try {
                connection1 = dataSource.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            tl.set(connection1);
            return  connection1;
        }
        return connection;
    }

    public static void releaseConnection(){
        Connection connection = tl.get();
        if ( connection != null){
            try {
                connection.close();
                tl.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void startTransaction(){
        Connection connection = JdbcUtils.getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollBack(){
        Connection connection = JdbcUtils.getConnection();
        try {
            connection.rollback();
			releaseConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void commit(){
        Connection connection = JdbcUtils.getConnection();
        try {
            connection.commit();
            releaseConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
